require("glon")

local default_spells = {
	10,
	20,
	30,
	40,
	50
}

function sql_initialize()
	tables_exist()
end
hook.Add("Initialize", "sqlinit", sql_initialize)

function sql_setup()
	if (sql.TableExists("player_info") && sql.TableExists("player_inventory")) then
	else
		if (!sql.TableExists("player_info")) then
			query = "CREATE TABLE player_info ( unique_id varchar(255), coins int )"
			result = sql.Query(query)
		end
		if (!sql.TableExists("player_inventory")) then
			query = "CREATE TABLE player_inventory ( unique_id varchar(255), inventory string )"
			result = sql.Query(query)
		end
	end
end

function sql_getcoins ( ply )
	unique_id = sql.QueryValue("SELECT unique_id FROM player_info WHERE unique_id = '"..steamID.."'")
	coins = sql.QueryValue("SELECT coins FROM player_info WHERE unique_id = '"..steamID.."'")
	ply:SetNWString("unique_id", unique_id)
	ply:SetNWInt("coins", coins)
end

function sql_getinventory ( ply )
	unique_id = sql.QueryValue("SELECT unique_id FROM player_info WHERE unique_id = '"..steamID.."'")
	coins = sql.QueryValue("SELECT coins FROM player_info WHERE unique_id = '"..steamID.."'")
	ply:SetNWString("inventory", coins)
end

function saveStat ( ply )
	inventory = ply:GetNWString("inventory")
	coins = ply:GetNWInt("coins")
	unique_id = ply:GetNWString ("SteamID")
	sql.Query("UPDATE player_inventory SET inventory = "..inventory.."")
	sql.Query("UPDATE player_info SET coins = "..coins.." WHERE unique_id = '"..unique_id.."'")
	ply:ChatPrint("Stats updated !")
end

function sql_newplayer( SteamID, ply )
 
	local steamID = SteamID
	sql.Query( "INSERT INTO player_info (`unique_id`, `coins`)VALUES ('"..steamID.."', '0')" )
	result = sql.Query( "SELECT unique_id, coins FROM player_info WHERE unique_id = '"..steamID.."'" )
	if (result) then

		sql.Query( "INSERT INTO player_skills (`unique_id`, `speech`, `fish`, `farm`)VALUES ('"..steamID.."', '1', '1', '1')" )
		result = sql.Query( "SELECT unique_id, speech, fish, farm FROM player_skills WHERE unique_id = '"..steamID.."'" )
		if (result) then
			Msg("Player account created !\n")
			sql_getcoins( ply )
			sql_value_skills( ply )
		end
	end
end

function sql_player_exists( ply )
 
	local steamID = ply:GetNWString("SteamID")
 
	result = sql.Query("SELECT unique_id, money FROM player_info WHERE unique_id = '"..steamID.."'")
	if (result) then
			sql_value_stats( ply ) // We will call this to retrieve the stats
			sql_value_skills( ply ) // We will call this to retrieve the skills
	else
		new_player( steamID, ply ) // Create a new player :D
	end
end

function sql_plyspawn( ply )
	timer.Create("Steam_id_delay", 1, 1, function()
		local SteamID = ply:SteamID()
		ply:SetNWString("SteamID", SteamID)
		timer.Create("SaveStat", 10, 0, function() saveStat( ply ) end)
		sql_playerexists( ply ) 
	end)
end
hook.Add( "PlayerInitialSpawn", "sql_plyspawn", sql_plyspawn )
